package rsj.service.account.dynamic;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 账号动态查询
 *
 * @author yuanqinglong
 * @since 2021/7/20 12:32
 */
@Component
public class AccountDynamicStatement {


    //**********************************账号列表*************************************//


    /**
     * 账户动态列表
     *
     * @return {@link String}
     */
    public String accountDynamicList(String customerName, String custId, String accountKey, Integer pageSize, Integer pageNow) {
        String sql = "SELECT CONCAT('RSJ',LPAD(cust_id::text,4,'0')) AS cust_id,\n" +
                "       cust_sname,org_id,org_user_name AS user_uname,org_type,\n" +
                "       aut_keyid,aut_signkey,aut_keyversion,aut_secretkey,user_status,\n" +
                "       org_type ,user_ctime FROM sys.sys_org\n" +
                "   LEFT JOIN sys.sys_user ON user_org_id = org_id LEFT JOIN sys.sys_authon ON aut_org_id = org_id  LEFT JOIN sys.sys_cust ON cust_id = org_cust_id WHERE 1=1 ";
        sql += this.dynamicConditions(customerName, custId, accountKey);
        sql += " ORDER BY user_ctime DESC OFFSET #{pageNow} LIMIT #{pageSize}";
        return sql;
    }


    /**
     * 账户动态列表统计
     *
     * @return {@link String}
     */
    public String accountDynamicCount(String customerName, String custId, String accountKey) {
        String sql = "SELECT COUNT(*) FROM sys.sys_org LEFT JOIN sys.sys_authon ON aut_org_id = org_id " +
                "  LEFT JOIN sys.sys_cust ON cust_id = org_cust_id WHERE 1=1 ";
        return sql + this.dynamicConditions(customerName, custId, accountKey);
    }


    /**
     * 动态条件下
     *
     * @param customerName 客户名称
     * @param custId       cust id
     * @param accountKey   账户关键
     * @return {@link String}
     */
    private String dynamicConditions(String customerName, String custId, String accountKey) {
        String condition = "";
        if (StringUtils.isNotBlank(customerName)) {
            condition += " AND cust_sname LIKE #{%customerName%} ";
        }
        if (StringUtils.isNotBlank(accountKey)) {
            condition += " AND aut_keyid LIKE #{%accountKey%}";
        }
        if (custId != null) {
            condition += " AND CONCAT('RSJ',LPAD(cust_id::text,4,'0')) LIKE #{%custId%}";
        }
        return condition;
    }


}
